<?php
// 预订管理
class OrderAction extends CommonAction {
    function _filter(&$map) {
       $key = trim($_REQUEST['keywords']);
         if(!empty($key)) {
             $map['order_no'] = array('like',"%".$key."%");
             $map['remark'] = array('like',"%".$key."%");//备注信息
             $map['comment'] = array('like',"%".$key."%");//留言信息
             $hotel_id = M('House')->where("name like '%".$key."%'")->field('id')->findAll();//其实还是house
             $houses = array();
             foreach ($hotel_id as $k1 => $value) {
                 $houses[$k1] = $value['id'];
             }
             $house_id = implode(",", $houses);
             if(!empty($hotel_id)) {
                 $map['house_id'] = array('in',$house_id);
             }
             $member_id1 = M('Member')->where("name like '%".$key."%'")->field('id')->findAll();
             $member_id2 = M('Member')->where("account like '%".$key."%'")->field('id')->findAll();//按用户名查询
             if(is_array($member_id1)){
                 is_array($member_id2)?$member_id = array_merge($member_id1, $member_id2):$member_id=$member_id1;
             }
             else if(is_array($member_id2)){
                 $member_id = $member_id2;
             }
             
             $member = array();
             foreach ($member_id as $k2 => $value) {
                 $member[$k2] = $value['id'];
             }
             $member_id = implode(",", $member);
             if(!empty($member_id)) {
                 $map['member_id'] = array('in',$member_id);
             }
             $Room = M('Room');
             $room_id = M('Room')->where("room_no like '%".$key."%'")->field('id')->findAll();
             $room = array();
             foreach ($room_id as $k3 => $value) {
                 $room[$k3] = $value['id'];
             }
             $room_id = implode(",", $room);
             if(!empty($room_id)) {
                 $map['room_id'] = array('in',$room_id);
             }
             //$map['update_time'] = $key;//保证分页跳转正常,注意不要查询update_time 可设置分页显示1000条每页。
             $map['_logic'] = "or";
         }
         $start_time = $_REQUEST['start_time'];
         $end_time = $_REQUEST['end_time'];
         if(!empty($start_time)){
             $map['start_time'] = array('egt',strtotime($start_time));
         }
         if(!empty($end_time)){
             $map['end_time'] = array('elt',strtotime($end_time));
         }
    }

    function _before_index(){
       $this->assign('status',C('orderStatus'));
    }

    function _before_add(){
        $this->assign('orderStatus',C('orderStatus'));
        $this ->assign('hotel',M('Hotel')->where('status = 1')->field('name,id')->findAll());
        $this->assign('member',M('Member')->where('status = 1')->findAll() );
    }

     function _before_edit(){
        $this->assign('orderStatus',C('orderStatus'));
        $this ->assign('hotel',M('Hotel')->where('status = 1')->field('name,id')->findAll());
        //$this->assign('member',M('Member')->where('status = 1')->findAll() );
    }

    public function insert(){
        $data = $_POST;
        $data['start_time'] =strtotime( $_POST['start_time'] );
        $data['end_time'] =strtotime( $_POST['end_time'] );
        //TODO 判断时间跨度是否超过一年半
        if(isTooLong(strtotime( $_POST['start_time'] ),strtotime( $_POST['end_time'] ))== false ){
            $this->error("时间跨度超过一年半，无效订单！");
        }
        if(!empty($_POST['room_id'])) {//预订时房间号可能还不确定
            $data['room_id'] = implode(",",$_POST['room_id'] );
            foreach($_POST['room_id'] as $key=>$value) {
                if( isOverlap( $value, strtotime( $_POST['start_time'] ),strtotime( $_POST['end_time'] ) ) ) {
                    $this->error("时间存在重叠！");
                    break;
                }
            }
        }
        
        $data['room_num'] = empty($_POST['room_id'])?$_POST['room_num']:count($_POST['room_id'] );
        $data['create_time'] = time();
        $data['order_no'] = $this->genManNo();
        $data['user_id'] = $_SESSION[C('USER_AUTH_KEY')];
        $data['check_status'] = 0;//永远设置为待审核

        $model = D('Order');
        if(false == $model ->create()){
            $this->error($model -> getError());
        }
        if(false !== $list = $model ->add($data)){
            $jumpUrl = $_REQUEST['jumpUrl'];
           if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl', $jumpUrl );
            $this-> success("新增订单成功！");
        }
        else{
             $this->error("新增订单失败！");
        }
    }

    public function update(){
        $data = $_POST;
        $data['start_time'] =strtotime( $_POST['start_time'] );
        $data['end_time'] =strtotime( $_POST['end_time'] );
         if(isTooLong(strtotime( $_POST['start_time'] ),strtotime( $_POST['end_time'] ))== false ){
            $this->error("时间跨度超过一年半，无效订单！");
        }
        if(!empty($_POST['room_id'])) {//预订时房间号可能还不确定
            $data['room_id'] = implode(",",$_POST['room_id'] );
            foreach($_POST['room_id'] as $key=>$value) {
                if( isOverlap( $value, strtotime( $_POST['start_time'] ),strtotime( $_POST['end_time'] ),$_POST['id'] ) ) {
                    $this->error("时间存在重叠！");
                    break;
                }
            }
        }
       
        $data['update_time'] = time();
        $data['user_id'] = $_SESSION[C('USER_AUTH_KEY')];
        $data['check_status'] = 0;//永远设置为待审核
        $data['room_num'] = empty($_POST['room_id'])?$_POST['room_num']:count($_POST['room_id'] );
        
        $model = D('Order');
        $old_status = $model->where('id = '.$_POST['id'])->getField('status');
        if(false == $model ->create()){
            $this->error($model -> getError());
        }
        if(false !== $list = $model ->save($data)){
            if($_POST['status'] != $old_status )
                updateLogStatus('order',intval($_POST['id']),0); //置该订单状态为待阅读

            $jumpUrl = $_REQUEST['jumpUrl'];
           if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl', $jumpUrl );
            //发送邮件通知客户
            $this->assign('user',getModelName(intval($_POST['member_id']),"Member"));
            $this->assign("content","您的订单号：".$_POST['order_no'].' 已经处理，<br/>状态为：<font color="red">'.getConfigVal($_POST['status'],"orderStatus").'</font>' );
           $content = $this->fetch('Email:reply');
           $to = getModelName($_POST['member_id'], "Member", "email" );
           //Log::write("会员ID：".$_POST['member_id']." 会员：".$to);
           sendMail("您在上海好家服务公寓的订单已经处理", $content, '上海好家服务公寓<info@okhome.cn>', $to );

            //如果预订单状态为已入住，则进入新建入住单流程
            if($_POST['status'] == 5 ){
                $this->redirect('/Checkin/add', 
                        array('orderid'=>$_POST['id'],'start_time'=>$_POST['start_time'],'end_time'=>$_POST['end_time']),
                                2,'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />预订单修改成功！2秒后将新增入住单~~');
            }else{
                $this-> success("订单修改成功！");
            }
        }
        else{
             $this->error("订单修改失败！");
        }
    }

    public function getHotelData(){
        $result = M('Hotel')->where('status = 1')->field('name')->findAll();
        $this->ajaxReturn($result);
    }

}
?>